<template>
  <div class="igmBox">
    <ul v-if="isLook" class="imgList">
      <li v-for="(item,index) in dataList" :key="index" class="img-item" @click="viewImage(index)">
        <img :src="item">
      </li>
    </ul>
    <ul v-else class="imgList">
      <li v-for="(item,index) in dataList" :key="index" class="img-item" @mouseleave="leave(item)" @mouseenter="enter(item)">
        <div v-show="item == hoverImg" class="hoverImg">
          <i class="el-icon-zoom-in" @click="viewImage(index)" />
          <i class="el-icon-delete" @click="handleRemove(item)" />
        </div>
        <div>
          <img :src="item">
        </div>
      </li>
    </ul>
    <el-upload
      v-if="!isLook"
      ref="uploadFile"
      :before-upload="checkFileType"
      :action="actionUrl"
      list-type="picture-card"
      :on-success="uploadSuccess"
      :class="{'hidd':isImgVisible}"
      :limit="limit"
      :headers="headers"
      :show-file-list="false"
      :file-list="fileArray"
    >
      <i slot="default" class="el-icon-plus" />
      <span class="el-upload-title">{{ placeholder }}</span>
    </el-upload>

    <!-- 图片预览 -->
    <el-image-viewer v-if="showViewer" :z-index="9999" :on-close="()=>{showViewer=false}" :url-list="newSrcList" />
  </div>
</template>

<script>
// 导入预览组件
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: 'Upload',
  components: {
    elImageViewer
  },
  props: {
    value: { // 编辑回显
      type: String,
      default: '',
      required: false
    },
    isLook: { // 是否是查看
      type: Boolean,
      default: false,
      required: false
    },
    limit: { // 最大上传图片数量
      type: Number,
      default: 1,
      required: false
    },
    url: {
      type: String,
      default: 'uploadImg.aspx?action=uploadOne',
      required: false
    },
    placeholder: {
      type: String,
      default: '上传图片',
      required: false
    }
  },
  data() {
    return {
      showViewer: false,
      srcList: [],
      newSrcList: [],
      dataList: [],
      isImgVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      hoverImg: '',
      fileArray: []
    }
  },
  computed: {
    actionUrl: function() {
      return `${this.baseUrl}/${this.url}`
    },
    headers() {
      // const token = this.$ls.get('TOKEN')
      const token = JSON.parse(localStorage.getItem('TOKEN')).value
      const head = { 'token': `${token}` }
      return head
    }
  },
  watch: {
    dataList: {
      handler(val) {
        this.$emit('update:value', val.join(','))
      },
      deep: true
    },
    value: {
      handler(val) {
        if (val) {
          this.dataList = val.split(',')
          if (this.isLook) {
            this.isImgVisible = true
          } else {
            if (this.dataList.length >= this.limit) {
              this.isImgVisible = true
            } else {
              this.isImgVisible = false
            }
          }
        } else {
          this.dataList = []
          this.fileArray = []
          if (this.isLook) {
            this.isImgVisible = true
          } else {
            this.isImgVisible = false
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {

  },
  methods: {
    // 预览图片的方法
    viewImage(index) {
      // if (!index) {
      //   this.$message.warning('暂无可查看的照片！')
      //   return
      // }
      if (Array.isArray(this.dataList)) {
        this.srcList = [...this.dataList]
      } else {
        this.srcList = [this.dataList]
      }
      const temp = []
      for (let i = 0; i < index; i++) {
        temp.push(this.srcList.shift())
      }
      this.newSrcList = this.srcList.concat(temp)
      this.showViewer = true
    },
    leave(val) {
      this.hoverImg = ''
    },
    enter(val) {
      this.hoverImg = val
    },
    // 删除
    handleRemove(val) {
      this.dataList = this.dataList.filter(item => item !== val)
      this.fileArray = this.fileArray.filter(item => item.url !== val)
      if (this.dataList.length < this.limit) {
        this.isImgVisible = false
      }
    },
    // 上传前钩子
    checkFileType(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      if (fileType !== '.jpg' && fileType !== '.jpeg' && fileType !== '.png' && fileType !== '.bmp' && fileType !== '.gif' && fileType !== '.webp') {
        this.$message.warning('请上传图片！')
        return false
      }
      return true
    },
    // 上传成功的回调
    uploadSuccess(response, file, fileList) {
      this.$refs.uploadFile.clearFiles() // 上传成功之后清除历史记录
      if (response.code === 1) {
        if (file.status === 'success') {
          const imgurl = this.baseUrl + file.response.data
          this.dataList.push(imgurl)
          const fileIitem = {
            name: file.name,
            url: imgurl
          }
          this.fileArray.push(fileIitem)
        }
      } else {
        this.$message.warning(response.message)
      }
      if (this.dataList.length >= this.limit) {
        this.isImgVisible = true
      }
    }
  }
}

</script>
<style scoped lang='scss'>
  .igmBox {
    display: flex;
    width: 100%;
    flex-wrap: wrap;
    .imgList {
        display: flex;
        height: auto;
        margin: 0;
        padding: 0;
        flex-wrap: wrap;
        .img-item {
            height: 100px;
            margin-right: 10px;
            position: relative;
            border:1px solid #d9d9d9;
            width:100px;
            img {
                height: 100px;
                width:100px;
                padding:8px;
            }
            color: #fff;
            .hoverImg {
                height: 100%;
                width: 100%;
                background: rgba(96, 98, 102, 0.5);
                text-align: center;
                position: absolute;
                top: 0;
                left: 0;
                display: flex;
                .el-icon-zoom-in {
                    height: 100%;
                    flex: 1;
                    line-height: 100px;
                    font-size: 20px;
                }
                .el-icon-delete {
                    height: 100%;
                    flex: 1;
                    line-height: 100px;
                    font-size: 20px;
                }
            }
        }
    }
    ::v-deep .el-upload-list__item{
      width:100px !important;
      height:100px !important;
    }
    .hidd {
        display: none;
    }
  }
</style>
<style lang="scss">
.igmBox .el-upload {
    width: 100px;
    height: 100px;
    position: relative;
    .el-upload-title {
        color: #777b85;
        font-size: 14px;
        display: inline-block;
        line-height: 50px;
    }
}
.igmBox .el-icon-plus {
    line-height: 100px;
    text-align: center;
    position: absolute;
    top: -12px;
    left: 37px;
}
</style>

